<template>
	<ls-page :hidden="true">
		<view class="bookTable-container">
			<view class="bookTable-main">
				<view class="bookTable-bottom-main" :style="backgroundStyle">
					<view class="bookTable-suggest" v-if="sugTable.length > 0">
						<view class="bookTable-suggest-title"></view>
						<view class="bookTable-suggest-main">
							<view :class="'main-item ' + (v.active ? 'active' : '') + ' '" v-for="(v, k) in sugTable"
								:key="k" @click="chooseSeat(k,v)">
								{{ v.name }}({{ v.maxpeople }}人)
							</view>
						</view>
					</view>

					<view class="bookTable-selected">
						<view class="bookTable-selected-table">
							<view class="bookTable-selected-big">{{ bookData.text ? bookData.text : '-- --' }}</view>
							<view class="bookTable-selected-small">
								容纳人数：{{ bookData.maxPeople ? bookData.maxPeople : '-- --' }}</view>
							<view class="bookTable-selected-small">
								推荐消费：{{ bookData.minConsume ? bookData.minConsume : '-- --' }}</view>
						</view>
						<view class="bookTable-selected-date">
							<view class="bookTable-selected-title" style="font-size: 36rpx">{{ dataTextM }}
								{{ dataTextD }}
							</view>
							<view class="bookTable-selected-subtitle">最晚预留时间：{{ dataLast }}</view>
						</view>
					</view>
					<view class="bookTable-top-main">
						<view class="bookTable-date">
							<scroll-view :scroll-x="true" class="scroll-x-none">
								<view class="bookTable-date-list">
									<view :class="'bookTable-date-item ' + (dateActive == k ? 'active' : '')"
										@click="daySelect(k)" v-for="(v, k) in dateList" :key="k">
										<view class="bookTable-date-name">{{ v.name }}</view>

										<view class="bookTable-date-time">{{ v.time }}</view>
									</view>
								</view>
							</scroll-view>
						</view>
						<view class="bookTable-select">
							<view class="bookTable-floor">
								<view :class="'bookTable-floor-item ' + (floorActive == k ? 'active' : '')"
									v-for="(v, k) in floorList" :key="k" @click="floorSelect(v)">{{ v.name }}</view>
							</view>
							<view class="bookTable-area">
								<movable-area :scale-area="true"
									:style="'height:' + bgHeight + 'rpx; width: 694rpx;margin:auto;overflow:hidden'">
									<movable-view :scale="true" direction="all" scale-max="2" scale-min="1"
										:out-of-bounds="true"
										:style="'height:' + bgHeight + 'rpx; width: ' + bgWidth + 'rpx;'">

										<view class="bookTable-area-holder"
											:style="'background-image:url(' + seatAreaBg + ')'">
											<view :data-index="k" class="bookTable-area-seat" :style="
								                               'left:' +
								                               v.left * rpxToPxRatio +
								                               'px;top:' +
								                               v.top * rpxToPxRatio +
								                               'px;width: ' +
								                               v.width * rpxToPxRatio +
								                               'px;height: ' +
								                               v.height * rpxToPxRatio +
								                               'px;transform: rotate(' +
								                               v.angle * rpxToPxRatio * 2 +
								                               'deg)'
								                           " @click.stop.prevent="onSeat(k)" v-for="(v, k) in seatList" :key="k">
												<image :src="v.nowIcon" class="bookTable-area-icon" />
												
											</view>
										</view>
									</movable-view>
								</movable-area>
							</view>
							<scroll-view :scroll-x="true" class="scroll-x-none">
								<view class="bookTable-type">
									<view class="bookTable-type-item" :class="{'active': tableActive == v.code}"
										@click="changeTable(v.code)" v-for="(v, k) in tableTypeList" :key="k">
										{{ v.name }}
									</view>
								</view>
							</scroll-view>
							<view class="bookTable-exp">
								<view class="bookTable-exp-item" v-for="(v, k) in expList" :key="k">
									<image class="bookTable-exp-icon" :src="v.icon"></image>

									<text class="bookTable-exp-text">{{ v.text }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="bookTable-form">
						<view class="bookTable-form-group">
							<view class="bookTable-form-heading">预订信息</view>
							<view class="bookTable-form-item">
								<view class="bookTable-form-cell">
									<view class="bookTable-form-label">电话</view>
									<view class="bookTable-form-value">
										<input class="bookTable-form-input" type="digit" placeholder="请输入电话"
											v-model="postForm.memberMobile" />
									</view>
								</view>
								<view class="bookTable-form-cell">
									<view class="bookTable-form-label">姓名</view>
									<view class="bookTable-form-value">
										<input class="bookTable-form-input" type="text" placeholder="请输入姓名"
											v-model="postForm.memberName" />
									</view>
								</view>
								<view class="bookTable-form-cell stepper">
									<view class="bookTable-form-label">人数</view>
									<view class="bookTable-form-value">
										<order-number-box :max="1000" :min="0" v-model="postForm.peopleNum" />
									</view>
								</view>
								<view class="bookTable-form-cell">
									<view class="bookTable-form-label">性别</view>
									<view class="bookTable-form-value" style="width: 230rpx;">
										<view class="" style="display: flex;justify-content: space-between;">
											<view class="booktable-item-radios" v-for="(item, index) in bookradios"
												:key="index" @click="bookradiosChange(index)">
												<image slot="icon"
													:src="radiosCruut == item.name ? icon.active : icon.normal"
													class="bookTable-form-radio" />
												<text>{{ item.text }}</text>
											</view>
										</view>


									</view>
								</view>
								<view class="bookTable-form-cell">
									<view class="bookTable-form-label">到店时间</view>
									<view class="bookTable-form-value" @click="toggleTimeShow">
										{{ postForm.reserveTime }}
									</view>
								</view>
							</view>
						</view>
						<view class="bookTable-form-group">
							<view class="bookTable-form-heading">预订模式</view>
							<view class="bookTable-form-item">
								<view class="bookTable-form-cell">
									<view class="bookTable-form-label" v-if="!isPayBook">免费预订</view>
									<view class="bookTable-form-label" v-if="isPayBook">付费预订</view>
									<view class="bookTable-form-value">
										<view class="bookTable-form-text" v-if="!isPayBook">免费预订</view>
										<view class="bookTable-form-text" v-if="isPayBook">￥{{ bookAmt }}</view>
									</view>
								</view>
							</view>
						</view>
						<view class="bookTable-form-group">
							<view class="bookTable-form-heading">备注</view>
							<view class="bookTable-form-item noPadding">
								<van-field custom-class="bookTable-form-textarea" placeholder-style="color:#666666"
									type="textarea" placeholder="请输入备注" maxlength="100" :show-word-limit="true"
									v-model="postForm.remark" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="bookTable-footer">
				<view class="bookTable-footer-info">
					<view class="bookTable-footer-title">
						<view class="bookTable-footer-label">
							订金：
							<text class="bookTable-footer-yd-price">￥{{ bookAmt }}</text>
						</view>
					</view>
					<view class="bookTable-footer-subtitle" v-if="bookData.text">
						{{ bookData.text }}（{{ bookData.maxPeople }}人桌）
					</view>
					<view class="bookTable-footer-subtitle" v-else>桌号：-- --</view>
				</view>
				<view class="bookTable-footer-control" style="display: flex; flex-direction: row; align-items: center">
					<view class="book-btn" style="color: #212121; margin-right: 50rpx; font-size: 30rpx"
						@click="submitBook" v-if="!isPayBook">直接预订</view>
					<view class="book-btn" style="margin-right: 50rpx; font-size: 30rpx"
						@click="choosePay" v-if="isPayBook">直接预订</view>
					<!-- <view class="yd-sub-btn">
						去预点单
					</view> -->
				</view>
			</view>
		</view>
		<up-datetime-picker title="选择时间" :show="startTimeShow" v-model="startTime" :closeOnClickOverlay="true"
			@close="startTimeShow = false" mode="time" @cancel="startTimeShow = false"
			@confirm="startTimeConfirm"></up-datetime-picker>

		<x-popup class="x-popup" :show="payShow" position="bottom" @close="payShow = false" :closeOnClickOverlay="true"
			custom-style="background-color: #2E2E2E;border-radius: 48rpx 48rpx 0 0;">
			<view class="orderPay-container">
				<view class="orderPay-main">
					<view :class="'orderPay-pay-card ' + (toolCard.cardType == 2 ? 'spe' : '')"
						:style="'background-image: url(' + toolCard.backgroundAtt2 + ');'">
						<view class="pay-card-top">
							<view :class="'top-left ' + (toolCard.cardType == 2 ? 'spe' : '')">
								<view class="top-left-title">{{ toolCard.carName }}</view>
								<view class="top-left-value">NO.{{ toolCard.code }}</view>
							</view>
							<view class="top-right" @click="onChangeCard" v-if="cardLength > 1">
								{{ toolCard.cardType == 2 ? '切换品牌卡' : '切换门店卡' }}
							</view>
						</view>
						<view class="pay-card-center">
							<view class="center-left">
								<view class="left-value">
									{{ toolCard.currentAmtAct % 1 != 0 ? toolCard.currentAmtAct : toolCard.currentAmtAct + '.00' }}
								</view>
								<view class="left-title">会员余额</view>
							</view>
							<view class="center-right" @click="gotoStore">立即储值</view>
						</view>
						<view class="pay-card-bottom">金币余额：{{ toolCard.currentCoins }}</view>
					</view>

					<view class="orderPay-pay-title">支付方式</view>
					<view class="cm-card">
						<view class="orderPay-cell multi" @click="onSelect('member')" v-if="isVipPay">
							<view class="orderPay-cell-cover">
								<image class="orderPay-cell-image"
									src="https://oss.jtmckj.com/wmp/images/home/orderPay/i_icon_vipcard.png"></image>
							</view>
							<view class="orderPay-cell-info">
								<view class="orderPay-cell-title">会员卡支付</view>
								<view class="orderPay-cell-subtitle">
									<view class="orderPay-cell-can">会员本金：￥{{ toolCard.currentAmt }}</view>
								</view>
							</view>
							<view class="orderPay-cell-panel">
								<image class="orderPay-cell-checkbox"
									:src="selectedMember ? iconData.radioed : iconData.radio"></image>
							</view>
						</view>
						<view class="orderPay-cell single" @click="onSelect('wechat')" v-if="isWeChatPay">
							<view class="orderPay-cell-cover">
								<image class="orderPay-cell-image"
									src="https://oss.jtmckj.com/wmp/images/home/orderPay/i_icon_wechat.png"></image>
							</view>
							<view class="orderPay-cell-info">
								<view class="orderPay-cell-title">微信支付</view>
							</view>
							<view class="orderPay-cell-panel">
								<image class="orderPay-cell-radio" :src="wechatPay ? iconData.radioed : iconData.radio">
								</image>
							</view>
						</view>
						<view class="orderPay-cell single" style="border: none" @click="onSelect('ali')"
							v-if="isWeChatPay">
							<view class="orderPay-cell-cover">
								<image class="orderPay-cell-image"
									src="https://oss.jtmckj.com/wmp/qnjg/order/i_icon_ali.png"></image>
							</view>
							<view class="orderPay-cell-info">
								<view class="orderPay-cell-title">支付宝支付</view>
							</view>
							<view class="orderPay-cell-panel">
								<image class="orderPay-cell-radio" :src="aliPay ? iconData.radioed : iconData.radio">
								</image>
							</view>
						</view>
					</view>
				</view>

				<view class="orderPay-footer">
					<view class="orderPay-footer-main">
						<view class="orderPay-footer-digit">
							<view class="orderPay-footer-money">
								<text class="orderPay-footer-money__assist">￥</text>
								<text class="orderPay-footer-money__num">{{ bookAmt }}</text>
							</view>
						</view>
						<view class="orderPay-footer-panel">
							<view class="fufei" @click="$u.throttle(onPay, 800)" >
								付费预订
							</view>
						</view>
					</view>
				</view>
			</view>
		</x-popup>
	</ls-page>
</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad, onUnload, onShow, onHide } from '@dcloudio/uni-app';
	import { HFiveAppObjProcess, HFiveMemberAppObjProcess } from '@/api/public.js'
	import dayjs from 'dayjs'
	import 'dayjs/locale/zh-cn'; // 引入中文语言包
	dayjs.locale('zh-cn');
	import wx from "weixin-js-sdk";

	// import { useShopStore } from '@/store/shop.js';
	// const store = useShopStore();
	const themetype = uni.getStorageSync('themeInfo')?.type
	const shopInfo = uni.getStorageSync('shopInfo') //门店信息
	const userInfo = uni.getStorageSync('userInfo') //用户信息
	console.log(shopInfo, 'shopInfo--------------')
	console.log(userInfo, 'userInfo--------------')

	// -------------------------------------------------------初始化数据-----------------------------------------------------
	const icon = {
		normal: 'https://oss.jtmckj.com/wmp/images/center/my/i_radio_normal.png',
		active: themetype == '001' ? 'https://oss.jtmckj.com/h5-uniapp/qnig/my/i_radio_choose.png' : 'https://oss.jtmckj.com/wmp/kbq/common/i_radio_choose.png',
		normal_square: 'https://oss.jtmckj.com/wmp/images/common/i_checkbox_check.png',
		active_square: 'https://oss.jtmckj.com/wmp/kbq/common/i_square_choose.png',
	}
	const iconData = {
		radioed: themetype == '001'  ? 'https://oss.jtmckj.com/h5-uniapp/qnig/my/i_radio_choose.png' : "https://oss.jtmckj.com/wmp/kbq/common/i_radio_choose.png",
		radio: "https://oss.jtmckj.com/wmp/images/common/i_radio_check.png",
	}
	const bookData = ref({}) //页面底部预订人数信息
	//预订参数
	const postForm = ref({
		payType: '', // 002 微信  004会员卡
		amt: '', // 金额
		tradeNo: '', // 交易单号
		cardNo: '', // 会员卡号
		memberName: userInfo.name, // 会员名称 
		memberMobile: userInfo.mobile, // 手机号 
		peopleNum: 1, // 预订人数
		roomCode: '', // 房间号 
		minConsume: '0.00', //房台低消 
		remark: '', // 备注
		memberSex: userInfo.sex, // 性别
		reserveTime: dayjs().format('YYYY-MM-DD HH:mm:ss') // 到店时间
	})

	//楼层列表
	const floorList = ref([{
		name: '1F'
	}])

	const radiosCruut = ref(userInfo.sex) //用户性别
	const bookradios = ref([{
		text: '先生',
		name: "011001"
	}, {
		text: '女士',
		name: "011002"
	}])
	//日期筛选tab
	const dateList = ref([{
		name: '今日',
		time: dayjs().format('MM-DD')
	}, {
		name: '明日',
		time: dayjs().add(1, 'day').format('MM-DD')
	}, {
		name: '后天',
		time: dayjs().add(2, 'day').format('MM-DD')
	}, {
		name: dayjs().add(3, 'day').format('dddd'),
		time: dayjs().add(3, 'day').format('MM-DD')
	}, {
		name: dayjs().add(4, 'day').format('dddd'),
		time: dayjs().add(4, 'day').format('MM-DD')
	}, {
		name: dayjs().add(5, 'day').format('dddd'),
		time: dayjs().add(5, 'day').format('MM-DD')
	}, {
		name: dayjs().add(6, 'day').format('dddd'),
		time: dayjs().add(6, 'day').format('MM-DD')
	}])

	const expList = ref([{
		icon: 'https://oss.jtmckj.com/wmp/qnjg/pre/i_icon_free.png',
		text: '可选'
	}, {
		// icon: 'https://oss.jtmckj.com/wmp/kbq/book/i_icon_select.png',
		icon: themetype == '001' ? 'https://oss.jtmckj.com/h5-uniapp/qnig/booktable/qnjgbooktabel.png' : 'https://oss.jtmckj.com/h5-uniapp/center/kx-booktabel.png',
		text: '已选'
	}, {
		icon: 'https://oss.jtmckj.com/wmp/qnjg/pre/i_table_ban.png',
		text: '不可选'
	}])

	const dateActive = ref(0); // 当前选中的日期项
	postForm.value.reserveTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

	const dataTextD = ref(dayjs().format('dddd'))
	const dataTextM = ref(''); // 星期几
  
  
   // 获取系统信息
   const sysInfo = uni.getSystemInfoSync() || {};
   
   const statusBarHeight = sysInfo.statusBarHeight || 20; // 状态栏高度
   const custom = uni.getMenuButtonBoundingClientRect ? uni.getMenuButtonBoundingClientRect() : {};
   const navigationBarHeight = custom.height + (custom.top - statusBarHeight) * 2; // 导航栏高度
   
   // 总的头部高度
   // const topBarHeight = statusBarHeight + navigationBarHeight
   const topBarHeight = statusBarHeight; // 如果只需要状态栏高度，可以直接用这个
   
   // 屏幕宽度
   const screenWidth = sysInfo.screenWidth;
   
   // 计算每个rpx对应的像素值
   const rpxToPxRatio = screenWidth / 750; //图标整体放大缩小倍数

	const payShow = ref(false) //支付显示
	const brandCard = ref({}) //品牌卡
	const storeCard = ref({}) // 门店卡
	const toolCard = ref({}) // 显示的会员卡
	const selectedMember = ref(false) // 会员支付
	const wechatPay = ref(false) // 微信支付
	const isPayBook = ref(false) // 是否是付费预订
	const bookAmt = ref(0) // 付费预订金额
	const sugTable = ref([]) //桌台容纳人数
	const isVipPay = ref(false) // 是否允许vip支付
	const isReserveOrder = ref(false) // 是否关闭预订单
	const isWeChatPay = ref(false) // 是否允许微信支付
	const bookBack = ref('https://oss.jtmckj.com/wmp/kbq/book/i_back.png')
	const dataLast = ref(shopInfo.reserveStopTime) // 最迟到店时间 
	const backgroundStyle = ref(
		`background: url('https://oss.jtmckj.com/wmp/qnjg/pre/i_meng.png') no-repeat center top / 100%, url('${shopInfo.reserveBackground}') no-repeat center top / 100%;`
	) //页面背景图
	const floorActive = ref(0)
	const startTimeShow = ref(false) //开始时间选择器控制
	const startTime = ref('') //开始时间选择器控制
	const cardLength = ref(null)

	const seatAreaBg = ref(''); //座位背景
	const bgHeight = ref(0); //座位高度
	const bgWidth = ref(0); //座位宽度
	const seatList = ref([]); //座位列表
	const toolSeatList = ref([]); //过滤房台
	const tableTypeList = ref([]); //房台tab
	const tableActive = ref("") //全部散台默认选中
	const aliPay = ref(false)
	// -------------------------------------------------------初始化数据-----------------------------------------------------

	onLoad((options) => {
		bookBack.value = shopInfo.reserveBackground //预订背景
		createMap()
	})

	onShow(() => {
		const timeStr = shopInfo.reserveStopTime // 获取时间字符串
		const dateStr = dayjs().format('YYYY-MM-DD') // 获取当前日期字符串

		// 将日期和时间拼接成完整的时间字符串并解析为日期对象
		let combinedDateTime = dayjs(`${dateStr} ${timeStr}`, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
		postForm.value.reserveTime = combinedDateTime

		// 更新响应式数据
		isReserveOrder.value = shopInfo.isReserveOrder
		isVipPay.value = shopInfo.isVipPay
		isWeChatPay.value = shopInfo.isWeChatPay

		// 调用其他方法
		createMap()
		onInit()
		getSugTable()
	});


	//-------------------------------------------------------筛选事件-操作-----------------------------------------------------
	//性别选中
	const bookradiosChange = (i) => {
		radiosCruut.value = bookradios.value[i].name
	}

	// 选择日期的函数
	const daySelect = (index) => {
		const dayM = dateList.value[index].time; // 获取选中的日期的时间
		const dayD = dayjs().add(index, 'day').format('dddd'); // 获取星期几
		// 拼接当前时间和选中日期的完整时间
		const timeStr = dayjs().format('HH:mm:ss'); // 当前时间
		const dateStr = dayjs().add(index, 'day').format('YYYY-MM-DD'); // 选中日期
		const combinedDateTime = dayjs(`${dateStr} ${timeStr}`).format('YYYY-MM-DD HH:mm:ss');

		// 更新预定时间
		postForm.value.reserveTime = combinedDateTime;
		// 更新选中的日期
		dateActive.value = index;
		// 更新日期和时间信息
		dataTextM.value = dayM;
		dataTextD.value = dayD;

		// 调用生成桌位图
		createMap();
	};

	//跳转储值
	const gotoStore = () => {
		uni.navigateTo({
			url: '/subpkg/view/centerStore/centerStore'
		})
	}

	//全部&散台过滤
	const changeTable = (code) => {
		if (code) {
			const arr = toolSeatList.value.filter(item => item.typeCode === code)
			seatList.value = arr
			tableActive.value = code
		} else {
			seatList.value = toolSeatList.value
			tableActive.value = ''
		}
	}

	// 选中推荐房台
	const chooseSeat = (index, item) => {
		// 清空之前选中的状态
		sugTable.value.forEach(v => {
			v.active = false
		})

		seatList.value.forEach(v => {
			if (v.nowIcon === v.selectedIcon) {
				v.nowIcon = v.defaultIcon
			}
		})

		// 设置当前选中的房台
		sugTable.value[index].active = !sugTable.value[index].active

		// 更新选中的房台信息
		bookData.value = {
			id: item.code,
			text: item.name,
			maxPeople: item.maxpeople,
			minConsume: item.minConsume
		}

	}

	// 楼层选择
	const floorSelect = (v) => {
		console.log(v)
	}

	// 时间选择开启
	const toggleTimeShow = () => {
		startTimeShow.value = true
	}

	// 时间选择确认方法
	const startTimeConfirm = (e) => {
		console.log(e,'dasdas')
		// 获取预订时间的年月日部分
		const dateStr = dayjs(postForm.value.reserveTime).format('YYYY-MM-DD')
		// // 将日期和时间拼接起来并格式化
		const combinedDateTime = dayjs(`${dateStr} ${e.value}`, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
		// // 更新预订时间
		postForm.value.reserveTime = combinedDateTime
		// 隐藏时间选择框
		startTimeShow.value = false
	}

	//效验手机号
	const validateMobile = (mobile) => {
		const reg = /^1[3-9]\d{9}$/;
		if (!reg.test(mobile)) {
			uni.$u.toast('请输入有效的手机号码')
			return false
		}
		return true
	}

	//-------------------------------------------------------筛选事件-操作-----------------------------------------------------


	//-------------------------------------------------------处理点击座位的事件-----------------------------------------------------
	const onSeat = (index) => {
		const seat = seatList.value[index];
		console.log(seat, '选中座位的数据')
		// 如果座位已售出，则不进行操作
		if (seat.nowIcon === seat.soldedIcon) return;

		// 更新其他座位状态
		seatList.value.forEach((seatItem, seatIdx) => {
			if (seatItem.nowIcon === seatItem.selectedIcon && seatIdx !== index) {
				seatItem.nowIcon = seatItem.defaultIcon; // 恢复其他已选座位的状态
			}
			if (seatIdx === index) {
				// 如果当前座位已经选中，则取消选中
				if (seatItem.nowIcon === seatItem.selectedIcon) {
					seatItem.nowIcon = seatItem.defaultIcon;
				} else {
					seatItem.nowIcon = seatItem.selectedIcon;
				}
			}
		});

		// 如果有建议表，取消其选中状态
		sugTable.value.forEach(v => {
			v.active = false;
		});

		bookData.value = seat.nowIcon === seat.selectedIcon ? seat : {};
		isPayBook.value = seat.isReservePay;
		console.log(isPayBook.value, 'isPayBook.value--------')
		bookAmt.value = seat.reservePayAmt;
	};

	// -------------------------------------------------------生成桌位图-----------------------------------------------------
	const createMap = async () => {
		try {
			const res = await HFiveMemberAppObjProcess({
				"functionName": "GetBaseConfigInfo_H5",
				"contentData": ""
			});
			console.log(res, 'res1----------')
			// 设置背景数据
			seatAreaBg.value = res.orgStageBackgroundImage;
			bgHeight.value = res.orgStageBackHeight;
			bgWidth.value = res.orgStageBackWidth;
			
			// bgHeight.value = 1381
			// bgWidth.value = 1714;

			// 设置座位类型列表
			const seatTypeList = {
				orgTableActive: res.orgTableActive,
				orgTableBan: res.orgTableBan,
				orgTableFree: res.orgTableFree,
			};

			// 处理座位数据
			const seatListData = await prosessSeatList(res.orgStageJson, seatTypeList);

			// 更新视图数据
			seatList.value = seatListData;
			toolSeatList.value = seatListData;

			console.log(seatList.value, ' seatList.value ')
			console.log(toolSeatList.value, ' toolSeatList.value  ')
		} catch (error) {
			console.error('Error creating map:', error);
		}
	};

	// -------------------------------------------------------初始化桌位数据-----------------------------------------------------
	const prosessSeatList = async (orgStageJson, seatTypeList) => {
		const seatListData = JSON.parse(orgStageJson).filter(item => item.left >= 0); // x轴大于0的才显示
		// 获取房间预定数据
		const tableRes = await HFiveMemberAppObjProcess({
			"functionName": "GetReserveRoomList_H5",
			"contentData": { "reserveTime": postForm.value.reserveTime }
		});
		const tableInfo = tableRes;
		// 遍历房间信息更新座位状态
		tableInfo.forEach(area => {
			area.areaRooms.forEach(room => {
				const seat = seatListData.find(seat => seat.id === room.roomCode);
				if (seat) {
					seat.roomState = room.roomState;
					seat.roomStateDesc = room.roomStateDesc;
					seat.maxPeople = room.maxPeople;
					seat.minConsume = room.minConsume;
					seat.typeName = room.typeName;
					seat.typeCode = room.typeCode;
					seat.isReservePay = room.isReservePay;
					seat.reservePayAmt = room.reservePayAmt;
				}
			});
		});

		//-------------------------------------------------------设置座位图标-----------------------------------------------------
		seatListData.forEach(seat => {
			if (seat.roomState === "0") {
				seat.nowIcon = seatTypeList.orgTableFree;
			} else {
				seat.nowIcon = seatTypeList.orgTableBan;
			}
			seat.selectedIcon = seatTypeList.orgTableActive;
			seat.soldedIcon = seatTypeList.orgTableBan;
			seat.defaultIcon = seatTypeList.orgTableFree;
		});

		// 房台类型分类去重
		const uniqueArray = Array.from(
			new Map(
				seatListData.map(item => [item.typeCode, item])
			).values()
		).map(item => ({ code: item.typeCode, name: item.typeName }));

		uniqueArray.unshift({ name: '全部', code: '' });

		tableTypeList.value = uniqueArray.filter(item => item.code !== undefined);
		return seatListData;
	};

	//-------------------------------------------------------提交预订-----------------------------------------------------
	const submitBook = async (tradeNo) => {
		const { id } = bookData.value;
		console.log(bookData.value,'bookData.value')
		if (!id) {
			uni.$u.toast('请选择桌台')
			return;
		}

		if (!postForm.value.memberName) {
			uni.$u.toast('请输入姓名')
			return;
		}

		if (!postForm.value.reserveTime || postForm.value.reserveTime === '-- --') {
			uni.$u.toast('请选择到店时间')
			return;
		}

		uni.showLoading({
			title: '加载中',
			mask: true
		});

		postForm.value.roomCode = id;

		// 验证手机号
		if (!validateMobile(postForm.value.memberMobile)) return;

		if (isPayBook.value) {
			if (wechatPay.value) {
				postForm.value.payType = '002'; // 002 微信
				postForm.value.tradeNo = tradeNo; // 交易单号
			} else if (selectedMember.value) {
				postForm.value.payType = '004'; // 004 会员卡
				postForm.value.cardNo = toolCard.value.code; // 会员卡号
			}

			postForm.value.amt = bookAmt.value; // 金额
		}

		try {
			const res = await HFiveMemberAppObjProcess({
				functionName: 'AddReserveRoom_H5',
				contentData: postForm.value
			});
			// 预订成功后更新页面状态
			uni.hideLoading();
			uni.$u.toast('预订成功')
			payShow.value = false
			uni.navigateTo({
				url: '/subpkg/view/myreserVation/myreserVation'
			});
		} catch (error) {
			uni.hideLoading();
			// uni.$u.toast('预订失败，请稍后重试')
		}
	}

	//-------------------------------------------------------获取会员信息-----------------------------------------------------
	const onInit = () => {
		HFiveMemberAppObjProcess({ functionName: "MemberInfo_H5", contentData: "" })
			.then((res) => {
				console.log(res, 'sdadafdsf=-=======')
				// 设置响应式数据
				cardLength.value = res.length
				toolCard.value = res[0]
				// 遍历结果并根据 cardType 设置品牌卡和门店卡
				res.map((item) => {
					if (item.cardType == 1) {
						// 品牌卡
						brandCard.value = item
					} else {
						// 门店卡
						storeCard.value = item
					}
				})
			})
			.catch((err) => {
				console.error('获取会员信息失败:', err)
			})
	}


	//-------------------------------------------------------获取推荐桌台-----------------------------------------------------
	const getSugTable = () => {
		HFiveMemberAppObjProcess({ functionName: "GetRecommendRoom_H5", contentData: "" })
			.then((res) => {
				if (res) {
					res.map(v => {
						v.active = false
					})
					sugTable.value = res.slice(0, 3)
					console.log(sugTable.value, 'sugTable.value----')
				}
			})
			.catch((err) => {
				console.error('获取会员信息失败:', err)
			})
	}

	//-------------------------------------------------------选择支付方式-----------------------------------------------------
	const choosePay = () => {
		const { id } = bookData.value
		console.log(bookData.value, 'bookData.value')
		if (!id) {
			uni.$u.toast('请选择桌台')
			return
		}

		if (!postForm.value.memberName) {
			uni.$u.toast('请输入姓名')
			return
		}

		if (!postForm.value.reserveTime || postForm.value.reserveTime === '-- --') {
			uni.$u.toast('请选择到店时间')
			return
		}

		if (!validateMobile(postForm.value.memberMobile)) return

		// 显示支付弹框
		payShow.value = true
	}

	//-------------------------------------------------------支付方式选择-----------------------------------------------------
	const onSelect = (type) => {
		if (type === "member") {
			// 如果余额小于等于 0，提示没有余额
			if (toolCard.value.currentAmt <= 0) {
				uni.$u.toast('暂无余额抵扣')
				return;
			}
			// 选择会员支付
			selectedMember.value = true;
			wechatPay.value = false;
			aliPay.value = false
		} else if (type === "wechat") {
			// 选择微信支付
			selectedMember.value = false;
			wechatPay.value = true;
			aliPay.value = false
		} else {
			aliPay.value = true
			wechatPay.value = false
			selectedMember.value = false;
		}
	};

	//-------------------------------------------------------付费预订-----------------------------------------------------
	const onPay = async () => {
		if (!wechatPay.value && !selectedMember.value && !aliPay.value) {
			uni.$u.toast('请选择支付方式')
			return
		}

		uni.showLoading({
			title: '加载中',
			mask: true
		});
		
		if (isPayBook.value) {
			if (wechatPay.value) {
				postForm.value.payType = '002'; // 002 微信
				postForm.value.amt = bookAmt.value;
				postForm.value.roomCode = bookData.value.id
			} else if(aliPay.value) {
				postForm.value.payType = '003'; // 003 支付宝
				postForm.value.amt = bookAmt.value;
				postForm.value.roomCode = bookData.value.id
			}
		}
		
	//预定验证
	let modalParam = {
		"functionName": "CheckReserve_H5",
		"contentData": { "memberMobile": postForm.value.memberMobile,
		"reserveTime":dayjs().format('YYYY-MM-DD HH:mm:ss')
		               }
	}
	const resParam = await HFiveMemberAppObjProcess(modalParam)
	
		if (wechatPay.value) { // 微信支付
			HFiveMemberAppObjProcess({ functionName: "ReservePay_H5", "contentData": { "fee": bookAmt.value} })
				.then((res) => {
					uni.hideLoading();
					console.log(res)
					if (res) {	
						postForm.value.tradeNo = res.tradeNo
						console.log(postForm.value,'postForm.value')
							try {
								const paymentRes =  HFiveMemberAppObjProcess({ functionName: "TemporaryReservePay_H5",contentData:postForm.value })
								wxPay(res)
							} catch (error) {
								uni.showToast({
									title: '支付失败，请联系服务员',
									icon: "none",
									duration: 2000,
								});
							}
						;
					}
				});

		} else if (aliPay.value) { // 支付宝支付
			let params = {
				cardNo: uni.getStorageSync('cardInfo').code,
				fee: bookAmt.value
			}
			const paymentRes = await HFiveMemberAppObjProcess({ functionName: "AliReservePay_H5",contentData: params })
			uni.hideLoading();
			console.log(postForm.value,'postForm.value-------------11111111')
			postForm.value.tradeNo = paymentRes.tradeNo
			try {
				HFiveMemberAppObjProcess({ functionName: "TemporaryReservePay_H5",contentData:postForm.value })
				uni.navigateTo({
					url: '/pagesOrder/view/pay/alipay?paymentRes=' + paymentRes.qr_code + '&from=bookTable'
				})
				payShow.value = false
			} catch (error) {
				uni.showToast({
					title: '支付失败，请联系服务员',
					icon: "none",
					duration: 2000,
				});
				payShow.value = false
			}
			
			

		} else {
			submitBook()
		}

	}

	//-------------------------------------------------------微信支付-----------------------------------------------------
	const wxPay = (payRes) => {
		wx.config({
			debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
			appId: payRes.appId, // 必填，公众号的唯一标识
			timestamp: payRes.timeStamp, // 必填，生成签名的时间戳
			nonceStr: payRes.nonceStr, // 必填，生成签名的随机串
			signature: payRes.paySign, // 必填，签名
			jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表 
		});
		wx.ready(() => {
			wx.chooseWXPay({
				appId: payRes.appId, // 必填，公众号的唯一标识
				timestamp: payRes.timeStamp, // 必填，生成签名的时间戳
				nonceStr: payRes.nonceStr, // 必填，生成签名的随机串
				package: payRes.package, // 统一支付接口返回的prepay_id参数值，提交格式如:prepay_id=|*|*|*)
				signType: payRes.signType, // 签名方式，根据后端返回就行，一般默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: payRes.paySign, // 必填，支付签名
				success: function(res) {
					payShow.value = false
					uni.hideLoading();
					uni.navigateTo({
						url: '/subpkg/view/myreserVation/myreserVation'
					});
				},
				cancel: function(payRes) {

				},
				fail: function(err) {
					uni.showToast({
						title: err,
						icon: "none",
						duration: 2000,
					});
				}
			});
		});
	}

	// 切换会员卡
	const onChangeCard = () => {
		if (toolCard.value.cardType == 1) {
			toolCard.value = storeCard.value
		} else {
			toolCard.value = brandCard.value
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../style/orderPay.scss";
</style>